<template>
  <div class="addcourse-main">
    <el-button type="primary" class="addcourse-button" @click="showAddDialog">预约实验</el-button>

    <!-- 新增课程的对话框 -->
    <el-dialog title="预约实验" v-model="editDialogVisible" style="max-width: 800px">
      <el-form :model="addForm" label-width="80px">
        <!-- 选择课程名称 -->
        <el-form-item label="课程名称" style="">
          <el-select v-model="addForm.cid" placeholder="请选择课程名称">
            <el-option
              v-for="item in coursesR"
              :key="item.cid"
              :label="item.name"
              :value="item.cid" />
          </el-select>
          <span style="margin-right: 5px">剩余学时:</span>
          {{ getCourse(addForm.cid!)?.remainhours }}
        </el-form-item>

        <!-- 选择预约实验室 -->
        <el-form-item label="实 验 室" style="align-items: center">
          <div>
            <el-radio-group v-model="addForm.room" style="">
              <el-radio-button label="905实验室" value="905" />
              <el-radio-button label="906实验室" value="906" />
              <el-radio-button label="907实验室" value="907" />
              <el-radio-button label="908实验室" value="908" />
            </el-radio-group>
          </div>
        </el-form-item>

        <!-- 选择预约周次 1~18周可选 -->
        <el-form-item label="预约周次" style="margin-bottom: 25px">
          <div class="slider-demo-block">
            <el-slider v-model="week" range :marks="marks" :min="1" :max="18" />
          </div>
        </el-form-item>

        <!-- 选择预约星期 星期一到星期日可选 -->
        <el-form-item label="预约星期" style="align-items: center">
          <div>
            <el-radio-group v-model="addForm.day" style="">
              <el-radio-button label="星期一" value="星期一" />
              <el-radio-button label="星期二" value="星期二" />
              <el-radio-button label="星期三" value="星期三" />
              <el-radio-button label="星期四" value="星期四" />
              <el-radio-button label="星期五" value="星期五" />
              <el-radio-button label="星期六" value="星期六" />
              <el-radio-button label="星期日" value="星期日" />
            </el-radio-group>
          </div>
        </el-form-item>

        <!-- 选择预约节次 12/34/56/78可选 -->
        <el-form-item label="预约节次">
          <div style="">
            <el-radio-group v-model="jc">
              <el-radio value="1" border>1~2节</el-radio>
              <el-radio value="2" border>3~4节</el-radio>
              <el-radio value="3" border>5~6节</el-radio>
              <el-radio value="4" border>7~8节</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveYY">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { courseStore } from '@/stores/course'
import { reactive, ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { loginStore } from '@/stores/user'
import type { Ytime } from '@/type'
import type { CSSProperties } from 'vue'
import { ytimeStore } from '@/stores/ytime'

interface Mark {
  style: CSSProperties
  label: string
}
type Marks = Record<number, Mark | string>

const marks = reactive<Marks>({
  1: {
    style: {
      color: '#1989FA'
    },
    label: '第1周'
  },
  5: '第5周',
  10: '第10周',
  14: '第14周',
  18: {
    style: {
      color: '#1989FA'
    },
    label: '第18周'
  }
})
// 获取当前登录老师信息,含name,uid
const userS = loginStore().userS
// 获取store缓存的引用，为当前登录老师的课程
const coursesR = courseStore().coursesS
console.log(coursesR)
// 获取store缓存的引用，为全部已预约的时间表
const ytimesR = ytimeStore().ytimesS

// 添加对话框显示标志
const editDialogVisible = ref(false)

// 预约周次
const week = ref([5, 10])

// 预约节次
const jc = ref('0')

// 预约信息的表单
const addForm = ref<Ytime>({
  uid: userS.value.uid,
  // cid: ,
  tname: userS.value.name,
  cname: '',
  room: '',
  start: week.value[0],
  end: week.value[1],
  day: '',
  time: []
})

// 根据jc给 time赋值
const mappedTime = computed(() => {
  switch (jc.value) {
    case '1':
      return [1, 2]
    case '2':
      return [3, 4]
    case '3':
      return [5, 6]
    case '4':
      return [7, 8]
    default:
      return []
  }
})
// 监听 周次 的变化，更新 addForm.start / addForm.end
watch(week, (newValue) => {
  console.log('week:' + newValue)
  addForm.value.start = newValue[0]
  addForm.value.end = newValue[1]
  console.log('start:' + addForm.value.start)
  console.log('end:' + addForm.value.end)
  console.log('星期:' + addForm.value.day)
})

// 监听 节次 的变化，更新 addForm.time
watch(jc, (newValue) => {
  console.log(newValue)
  addForm.value.time = mappedTime.value
  console.log('节次:' + addForm.value.time)
})

// 显示添加对话框
const showAddDialog = () => {
  editDialogVisible.value = true
}

// 获取选择的课程, 基于cid查询，即使课程修改名字也不影响
const getCourse = (cid: number) => {
  const selectedCourse = coursesR.value.find((course) => course.cid === cid)
  return selectedCourse
}

// // 获取选择课程的剩余学时 (可预约的总时长)
// const getRemainHours = (cname: string) => {
//   const selectedCourse = coursesR.value.find((course) => course.name === cname)
//   return selectedCourse ? selectedCourse.remainhours : 0
// }

// // 获取选择课程的课程id
// const getCid = (cname: string) => {
//   const selectedCourse = coursesR.value.find((course) => course.name === cname)
//   return selectedCourse ? selectedCourse.cid : 0
// }

// 实验室时间冲突
// 个人时间冲突
// 检查预约表单与已有预约时间表的冲突
function checkConflict(addForm: Ytime, ytimes: Ytime[]): string {
  for (const ytime of ytimes) {
    // 实验室时间冲突
    if (addForm.room === ytime.room) {
      if (
        // 星期相同
        addForm.day === ytime.day &&
        // 节次相同
        addForm.time![0] === ytime.time![0] &&
        addForm.time![1] === ytime.time![1]
      ) {
        // 周次有交集
        if (!(addForm.end! < ytime.start! || addForm.start! > ytime.end!)) {
          // 存在冲突
          return '实验室时间冲突'
        }
      }
    }
    // 个人时间冲突
    if (addForm.uid === ytime.uid) {
      if (
        // 星期相同
        addForm.day === ytime.day &&
        // 节次相同
        addForm.time![0] === ytime.time![0] &&
        addForm.time![1] === ytime.time![1]
      ) {
        // 周次有交集
        if (!(addForm.end! < ytime.start! || addForm.start! > ytime.end!)) {
          // 存在冲突
          return '个人时间冲突'
        }
      }
    }
  }
  // 无冲突
  return '可预约'
}

// 保存预约信息
const saveYY = () => {
  // ***************** 错误检测 *******************
  // 未选课程
  if (!addForm.value.cid) {
    warn('警告! 请选择预约课程')
    console.log('课程名:' + addForm.value.cname)
    return
  }

  // 计算预约的课时数量
  const appointmentHours = (week.value[1] - week.value[0] + 1) * 2
  // 获取选择的课程, 这里因为选了课程, addForm.value.cid一定有值
  const newCourse = getCourse(addForm.value.cid!)
  // 获取剩余学时
  const remainHours = newCourse?.remainhours
  console.log('更新剩余学时前的剩余时间：')
  console.log(remainHours)

  // 未选实验室
  if (!addForm.value.room) {
    warn('警告! 请选择预约实验室')
    console.log('实验室:' + addForm.value.room)
    return
  }

  // 未选星期
  if (!addForm.value.day) {
    warn('警告! 请选择预约星期')
    console.log('星期:' + addForm.value.day)
    return
  }

  // 未选节次
  if (addForm.value.time === undefined || addForm.value.time.length === 0) {
    warn('警告! 请选择预约节次')
    console.log('节次:' + addForm.value.time)
    return
  }

  // 课时为0
  if (appointmentHours === 0) {
    error('警告! 预约课时不可为0')
    return
  }

  // 预约时间 > 剩余学时，弹出警告,这里因为选了课程, remainHours一定有值
  if (appointmentHours > remainHours!) {
    error('错误! 预约学时不可超过剩余学时')
    console.log('预约时长:' + appointmentHours)
    console.log('剩余时长:' + remainHours)
    return // 退出函数，不保存更改
  }

  // 检查预约时间是否与已有预约时间冲突
  const conflictStatus = checkConflict(addForm.value, ytimesR.value)
  if (conflictStatus !== '可预约') {
    error('错误! ' + conflictStatus)
    return
  }

  // ********** 通过了所有的错误检测，进行预约结果保存 **************
  addForm.value.cname = newCourse?.name
  const newRemainHours = remainHours! - appointmentHours
  console.log('更新剩余学时前的新剩余时间：')
  console.log(newRemainHours)
  newCourse!.remainhours = newRemainHours
  console.log('更新剩余学时后的选择课程：')
  console.log(newCourse)
  // 在数组中查找待更新课程的索引
  const index = coursesR.value.findIndex((c) => c.cid === newCourse!.cid)
  // 如果找到了索引，更新课程的剩余学时
  if (index !== -1) {
    const updatedCourse = { ...newCourse, remainhours: newRemainHours }
    coursesR.value.splice(index, 1, updatedCourse)
  }
  console.log('更新剩余学时后的缓存：')
  console.log(coursesR)
  console.log('新加的预约单：')
  console.log(addForm)

  // 添加预约单到实验室预约缓存
  ytimesR.value.push(addForm.value)
  console.log('添加新预约单后的预约情况缓存：')
  console.log(ytimesR)
  console.log('添加新预约单后的905预约情况缓存：')
  const y905s = ytimeStore().ytimes905S
  console.log(y905s)

  // 还原预约表单为默认值
  // 预约周次
  week.value = [5, 10]
  // 预约节次
  jc.value = '0'
  addForm.value = {
    uid: userS.value.uid,
    cid: undefined,
    tname: userS.value.name,
    cname: '',
    room: '',
    start: week.value[0],
    end: week.value[1],
    day: '',
    time: []
  }

  //  关闭编辑对话框
  editDialogVisible.value = false
}
// 警告框
const warn = (mes: any) => {
  ElMessage({
    showClose: true,
    message: mes,
    type: 'warning'
  })
}

// 错误框
const error = (mes: any) => {
  ElMessage({
    showClose: true,
    message: mes,
    type: 'error'
  })
}
</script>
<style scoped>
.addcourse-main {
  margin: 10px 0;
}
.hours-text {
  color: red;
  margin-left: 3%;
}
.slider-demo-block {
  max-width: 600px;
  width: 100%;
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-top: 0;
  margin-left: 12px;
}
</style>
